package com.lx.controller;

import com.lx.entity.Address;
import com.lx.service.AddressService;
import com.lx.util.JwtUtil;
import com.lx.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/address")
public class AddressController {

    @Autowired
    AddressService addressService;

    /**
     * 获取用户所有收货地址
     */
    @PostMapping("/list")
    public List<Address> getAddressList(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        Integer userId = Integer.parseInt(params.get("userId").toString()) ;
        if (userId == null) {
            String token = request.getHeader("Authorization");
            userId = JwtUtil.getUserID(token);
            if(userId == null)
                throw new RuntimeException("用户ID不能为空");
        }
        return addressService.getAllAddresses(userId);
    }

    /**
     * 新增收货地址
     * 要求：必须传 province, city, district
     */
    @PostMapping("/add")
    public boolean addAddress(@RequestBody Address address) {
        // 校验地址数量是否超过16个
        int count = addressService.getAllAddresses(address.getUserId()).size();
        if (count >= 5) {
            return false;
        }

        // 拼接完整地址
        address.buildAddress();

        // 设置创建时间
        address.setCreateTime(new Date());

        return addressService.addAddress(address);
    }

    /**
     * 修改收货地址
     */
    @PostMapping("/update")
    public boolean updateAddress(@RequestBody Address address) {
        // 拼接完整地址
        address.buildAddress();
        return addressService.updateAddress(address);
    }

    /**
     * 删除收货地址（逻辑删除）
     */
    @PostMapping("/delete")
    public boolean deleteAddress(@RequestBody Map<String, Object> params) {
        Object idObj = params.get("id");
        Integer id = null;

        if (idObj instanceof Integer) {
            id = (Integer) idObj;
        } else if (idObj instanceof String) {
            try {
                id = Integer.parseInt((String) idObj);
            } catch (NumberFormatException e) {
                throw new RuntimeException("地址ID格式不正确");
            }
        } else if (idObj != null) {
            throw new RuntimeException("地址ID格式不正确");
        }
        if (id == null) {
            throw new RuntimeException("地址ID不能为空");
        }
        return addressService.deleteAddress(id);
    }

    /**
     * 设置默认地址
     */
    @PostMapping("/set-default")
    public boolean setDefaultAddress(@RequestBody Map<String, Object> params) {
        Integer userId = Integer.parseInt(params.get("userId").toString());
        Integer id =Integer.parseInt(params.get("id").toString());

        if (userId == null) {
            throw new RuntimeException("用户ID不能为空");
        }
        if (id == null) {
            throw new RuntimeException("地址ID不能为空");
        }

        return addressService.setDefaultAddress(userId, id);
    }

    /**
     * 查询单个地址详情
     */
    @PostMapping("/detail")
    public Address getAddressDetail(@RequestBody Map<String, Object> params) {
        Integer id = (Integer) params.get("id");
        if (id == null) {
            throw new RuntimeException("地址ID不能为空");
        }
        return addressService.getAddressById(id);
    }

    @PostMapping("/getUserId")
    public Result getUserId(String token) {
        if(token == null || "".equals(token)) return Result.error(5500, "用户尚未登录！");
        return Result.success().add("userId", JwtUtil.getUserID(token));

    }
}
